package com.fjnldx.mes.service.scheduling.alarm.rule.inspector.trigger;

import com.alibaba.fastjson.JSONObject;
import com.fjnldx.mes.domain.pojo.alarm.enums.TriggerConditionEnum;
import com.fjnldx.mes.domain.pojo.alarm.enums.TriggerTypeEnum;
import com.fjnldx.mes.service.scheduling.alarm.mapper.AlarmSchedulingMapper;
import com.fjnldx.mes.service.scheduling.alarm.model.MonitorModel;
import com.fjnldx.mes.service.scheduling.alarm.rule.inspector.contrast.AlarmContrast;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 立即触发
 */
@Service
public class ImmediateTrigger implements AlarmTrigger {

    @Resource
    private AlarmSchedulingMapper alarmSchedulingMapper;

    private final List<AlarmContrast> alarmContrastList;

    public ImmediateTrigger(List<AlarmContrast> alarmContrasts) {
        this.alarmContrastList = alarmContrasts;
    }

    @Override
    public TriggerTypeEnum TriggerType() {
        return TriggerTypeEnum.IMMEDIATE;
    }

    @Override
    public MonitorModel isTriggered(String cs, String tableName, String devSn, String triggerValue, String conditionSql) {
        JSONObject triggerConfig = JSONObject.parseObject(triggerValue);

        //对比操作符
        TriggerConditionEnum condition = triggerConfig.getObject("operator", TriggerConditionEnum.class);

        //标准值
        String standardValue = triggerConfig.getString("standard");

        //实时属性值
        String csValue = alarmSchedulingMapper.getCsFirstValue(cs, tableName, devSn, conditionSql);

        MonitorModel monitor = new MonitorModel();
        monitor.setStandard(standardValue);
        monitor.setCollect(csValue);
        monitor.setOperator(condition);
        List<AlarmContrast> alarmContrasts = alarmContrastList.stream().filter(contrast -> contrast.getCondition() == condition).collect(Collectors.toList());
        for (AlarmContrast alarmContrast : alarmContrasts) {
            if (alarmContrast.Contrast(csValue, standardValue)) {
                monitor.setWhetherTrigger(true);
                break;
            }
        }
        return monitor;
    }
}
